//
//  TBubbleMessageCell.m
//  TXIMSDK_TUIKit_iOS
//
//  Created by annidyfeng on 2019/5/22.
//

#import "LGBubbleMessageCell.h"
#import "TUICommonModel.h"
#import "TUIDefine.h"

@interface LGBubbleMessageCell()
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;
@property (nonatomic , strong)NSDateFormatter *weekformatter;
@property (nonatomic , strong)NSDateFormatter *hourformatter;
/**   */
@property (nonatomic , strong)NSDictionary *weekDic;
@end

@implementation LGBubbleMessageCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.weekDic =  @{@"Mon": @"周一", @"Tue": @"周二",@"Wed": @"周三",@"Thu": @"周四",@"Fri": @"周五", @"Sat": @"周六",@"Sun": @"周日"};
        //接收方气泡
        UIImage *incommingBubble = [[TUIImageCache sharedInstance] getResourceFromCache:TUIChatImagePath(@"ReceiverTextNodeBkg")];
        self.receiverBubble = [TUIChatDynamicImage(@"chat_bubble_receive_img", incommingBubble) resizableImageWithCapInsets:UIEdgeInsetsFromString(@"{8,8,8,8}") resizingMode:UIImageResizingModeStretch];
        
        //发送方气泡
        UIImage *outgoingBubble = [[TUIImageCache sharedInstance] getResourceFromCache:TUIChatImagePath(@"SenderTextNodeBkg")];
        self.senderBubble = [TUIChatDynamicImage(@"chat_bubble_send_img", outgoingBubble) resizableImageWithCapInsets:UIEdgeInsetsFromString(@"{12,12,12,12}") resizingMode:UIImageResizingModeStretch];
       
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = UIColor.clearColor;
        self.contentView.backgroundColor = UIColor.clearColor;

        [self.contentView addSubview:self.timeLabel];
        [self.contentView addSubview:self.avatarView];
        [self.contentView addSubview:self.nameLabel];
        [self.contentView addSubview:self.bubbleView];
    }
    return self;
}


-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    CGFloat topMargin = [LGNSString(dataDic[@"showTime"]) isEqualToString:@"Y"]?20:0;
    self.timeLabel.hidden = [LGNSString(dataDic[@"showTime"]) isEqualToString:@"Y"]?NO:YES;
    self.timeLabel.text = [self messageTime:[dataDic[@"message_time"] integerValue]];
    NSString *sender = LGNSString(dataDic[@"sender"]);
    if ([sender isEqualToString:@"member"]) {
        self.nameLabel.textAlignment = NSTextAlignmentLeft;
        self.bubbleView.image = self.receiverBubble;
        [self.avatarView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(viewPix(20)+topMargin);
            make.left.equalTo(self.contentView).offset(viewPix(12));
            make.width.height.equalTo(@(40));
        }];
        [self.nameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarView);
            make.left.equalTo(self.avatarView.mas_right).offset(viewPix(10));
            make.height.equalTo(@(20));
        }];
        [self.bubbleView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.mas_bottom).offset(viewPix(5));
            make.left.equalTo(self.nameLabel);
            make.width.equalTo(@(viewPix(30)));
            make.bottom.equalTo(self.contentView).offset(-viewPix(15));
        }];
    }else{
        self.nameLabel.textAlignment = NSTextAlignmentRight;
        self.bubbleView.image = self.senderBubble;
        [self.avatarView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(viewPix(20)+topMargin);
            make.right.equalTo(self.contentView).offset(-viewPix(12));
            make.width.height.equalTo(@(40));
        }];
        [self.nameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarView);
            make.right.equalTo(self.avatarView.mas_left).offset(-viewPix(10));
            make.height.equalTo(@(20));
        }];
        [self.bubbleView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.mas_bottom).offset(viewPix(5));
            make.right.equalTo(self.nameLabel);
            make.width.equalTo(@(viewPix(30)));
            make.bottom.equalTo(self.contentView).offset(-viewPix(15));
        }];
    }
    
    NSDictionary *customeDic = [ObjectTool jsonToObject:dataDic[@"data"]];
    customeDic = [ObjectTool jsonToObject:customeDic[@"CloudCustomData"]];
    if([sender isEqualToString:@"member"] &&  customeDic && [customeDic isKindOfClass:[NSDictionary class]] && [customeDic.allKeys count]>0 && [customeDic.allKeys containsObject:@"customMsg"]){
        customeDic = [ObjectTool jsonToObject:customeDic[@"customMsg"]];
        NSDictionary *patientDic = customeDic[@"patient"];
        self.nameLabel.text = LGNSString(patientDic[@"realname"]);
        UIImage *placeHolder = [patientDic[@"gender"] isEqualToString:@"男"]?defaultPatientMan:defaultPatientWomen;
        [self.avatarView sd_setImageWithURL:patientDic[@"avatar_url"] placeholderImage:placeHolder];
    }else{
        if ([dataDic[@"doctorInfo"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *doctorInfo = dataDic[@"doctorInfo"];
            self.nameLabel.text = LGNSString(doctorInfo[@"realname"]);
            [self.avatarView sd_setImageWithURL:[NSURL URLWithString:LGNSString(doctorInfo[@"realname"])] placeholderImage:defaultDoctorPic];
        }else{
            self.nameLabel.text = @"医生";
            [self.avatarView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:defaultDoctorPic];
        }
    }
}

//获取时间
-(NSString *)messageTime:(NSInteger)timestamp{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSDate *todayStart = [self startOfDayForDate:[NSDate date]];
    NSDate *yesterdayStart = [self startOfDayForDate:[NSDate dateWithTimeIntervalSinceNow:-24 * 60 * 60]];
    NSDate *dayBeforeYesterdayStart = [self startOfDayForDate:[NSDate dateWithTimeIntervalSinceNow:-2 * 24 * 60 * 60]];

    // 比较日期部分（忽略时间）
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:todayStart];
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];

    BOOL isToday = [todayComponents isEqual:dateComponents];
    
    BOOL isYesterday = [[calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:yesterdayStart] isEqual:dateComponents];
    
    BOOL isDayBeforeYesterday = [[calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:dayBeforeYesterdayStart] isEqual:dateComponents];
    
    // 判断是否本周（周一 00:00:00 ~ 周日 23:59:59）
    BOOL isThisWeek = [self isThisWeek:date];

    if (isToday) {
        return [self.hourformatter stringFromDate:date];
        
    } else if (isYesterday) {
        NSLog(@"昨天");
        return [NSString stringWithFormat:@"昨天 %@",[self.hourformatter stringFromDate:date]];
        
    } else if (isDayBeforeYesterday) {
        NSLog(@"前天");
        return [NSString stringWithFormat:@"前天 %@",[self.hourformatter stringFromDate:date]];
        
    } else if (isThisWeek) {
        NSLog(@"本周（非今天/昨天/前天）");
        NSString *key = [self.weekformatter stringFromDate:date];
        return [NSString stringWithFormat:@"%@ %@",[self.weekformatter stringFromDate:date],[self.hourformatter stringFromDate:date]];;
        
    } else {
        NSLog(@"更早的日期");
        return [self.formatter stringFromDate:date];
    }
}

- (NSDate *)startOfDayForDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    return [calendar dateFromComponents:components];
}

-(BOOL)isThisWeek:(NSDate *)date{
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2]; // 设置周一为一周的第一天（默认是周日）
    
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:today];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    
    // 计算本周的周一
    NSDate *startOfWeek = [calendar dateFromComponents:components];
    // 如果当前日期不是周一，则回退到上周一
    NSDateComponents *weekdayComponents = [calendar components:NSCalendarUnitWeekday fromDate:today];
    NSInteger daysToSubtract = (weekdayComponents.weekday - calendar.firstWeekday + 7) % 7;
    startOfWeek = [calendar dateByAddingUnit:NSCalendarUnitDay value:-daysToSubtract toDate:startOfWeek options:0];
    
    // 计算本周的周日（+6天）
    NSDate *endOfWeek = [calendar dateByAddingUnit:NSCalendarUnitDay value:6 toDate:startOfWeek options:0];
    // 设置时间为 23:59:59
    NSDateComponents *endComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:endOfWeek];
    [endComponents setHour:23];
    [endComponents setMinute:59];
    [endComponents setSecond:59];
    endOfWeek = [calendar dateFromComponents:endComponents];
    
    BOOL isThisWeek = ([date compare:startOfWeek] != NSOrderedAscending) && ([date compare:endOfWeek] != NSOrderedDescending);
    return isThisWeek;
}

#pragma mark
#pragma mark ====> 创建控件
-(UILabel *)timeLabel{
    if(!_timeLabel){
        _timeLabel = [UILabel lableWithText:@"" colorString:@"#666666" textFont:LGFont(14) textAlignment:NSTextAlignmentCenter lines:1];
        _timeLabel.frame = CGRectMake(0, viewPix(5), Screen_W, 20);
    }
    return _timeLabel;
}

-(UIImageView *)avatarView{
    if(!_avatarView){
        _avatarView = [[UIImageView alloc]init];
        _avatarView.contentMode = UIViewContentModeScaleAspectFill;
        _avatarView.userInteractionEnabled = YES;
        _avatarView.cornerRidus = 5;
//        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSelectMessageAvatar:)];
//        [_avatarView addGestureRecognizer:tap1];
    }
    return _avatarView;
}

-(UILabel *)nameLabel{
    if(!_nameLabel){
        _nameLabel = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _nameLabel;
}

-(UIImageView *)bubbleView{
    if(!_bubbleView){
        _bubbleView = [[UIImageView alloc]init];
        _bubbleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _bubbleView.userInteractionEnabled = YES;
    }
    return _bubbleView;
}

-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc]init];
        _formatter.dateFormat = @"yyyy/MM/dd HH:mm";
    }
    return _formatter;
}

-(NSDateFormatter *)hourformatter{
    if(!_hourformatter){
        _hourformatter = [[NSDateFormatter alloc]init];
        _hourformatter.dateFormat = @"HH:mm";
    }
    return _hourformatter;
}

-(NSDateFormatter *)weekformatter{
    if(!_weekformatter){
        _weekformatter = [[NSDateFormatter alloc]init];
        _weekformatter.dateFormat = @"E";
    }
    return _weekformatter;
}

@end
